<template>
	<div id="wrap">
		<van-nav-bar title="地图查找" />
         <div id="map"></div>
		 <div id="r-result">
			 <label>请输入:</label><input type="text" id="suggestId" size="20" class="input" />	
			 <button @click="savePoint">保存经纬度，返回场馆发布页</button> 
		 </div>

	</div>
</template>

<script>

import { NavBar } from 'vant';

export default {

	data(){
		return{
			map:null,
			point:null,
			marker:null
		}
	},

	mounted(){

		// 初始化地图;
		this.initMap();	

		// 初始化标注;
		this.initMarker();

		// 智能搜索
		this.initSearch();
		
	},

	methods:{
		
		// 将经纬度同步到状态中心; 
		savePoint(){
			console.log(this.point); 
			this.$store.commit('SAVE_POINT',this.point);
			this.$router.push('/create_venue');
		},
        
		initMap(){
			
			// 创建地图实例  
			this.map = new BMap.Map("map");
			
			// 创建点坐标  
			this.point = new BMap.Point(116.404, 39.915);
			
			// 初始化地图，设置中心点坐标和地图级别 
			this.map.centerAndZoom(this.point, 15);
			
			// 添加平移和缩放控件
			this.map.addControl(new BMap.NavigationControl());

		},

		// 初始化标注; 
        initMarker(){

			this.createMarker();
			
			this.map.addEventListener('click',(e)=>{
				
				console.log(e.point);
				this.point = e.point;
			    this.createMarker();
				
			})

		},

		createMarker(){

            this.map.removeOverlay(this.marker);
			this.marker = new BMap.Marker(this.point);           // 创建标注    
			this.map.addOverlay(this.marker);                     // 将标注添加到地图中 
			this.marker.enableDragging();   // 让标注可拖拽;
            this.marker.addEventListener("dragend", function(e){    
				console.log("当前位置：" + e.point.lng + ", " + e.point.lat);    
			})

		},

		// 搜索初始化;
		initSearch(){
			let ac = new BMap.Autocomplete({"input" : "suggestId","location" : this.map});

			// 对地图进行定位
			ac.addEventListener("onconfirm", e=> {
				let _value = e.item.value;
				console.log(_value);
				this.searchValue = _value.province + _value.city + _value.district + _value.street 
				+ _value.business;
				this.moveMap(this.searchValue);

			});
		},

		// 平移地图
		moveMap(address){

			let that = this;
			  
			let local = new BMap.LocalSearch(this.map, {
			
			    onSearchComplete(){
					console.log('complete');
					that.point = local.getResults().getPoi(0).point;
					that.map.panTo(that.point);
					that.createMarker();
				}
            
			});

            local.search(address);
             
		}


	}
}
</script>

<style lang="less" scoped>

#map{
	height: 500px;
}

#r-result{
	font-size: 28px;
	padding:20px;
}

.input{
	width:450px;
	margin: 15px;
	height: 50px;
}

.searchResult{
	 border:1px solid #C0C0C0;
	 width:450px;
	 height:auto; 
	 display:none;  
}


</style>